import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

# 导入并设置日志配置
from app.config.logging_config import setup_logging
setup_logging()

from app.config.settings import settings
# 导入路由模块
from app.routers import root, chat, health
from app.routers.audio import router as audio_router
# 导入音频管理器
from app.services.audio_manager import audio_manager

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.APP_NAME,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION
)

# 配置CORS中间件
# noinspection PyTypeChecker
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins_list,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"],  # 允许前端访问的响应头
    max_age=600,  # 预检请求结果缓存10分钟
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/audio", StaticFiles(directory="audio_files"), name="audio")

# 注册路由模块
app.include_router(root)
app.include_router(chat)
app.include_router(health)
app.include_router(audio_router)


# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化操作"""
    # 启动音频文件自动清理任务
    await audio_manager.start_auto_cleanup()
    print("🚀 应用启动完成，音频自动清理任务已启动")


# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理操作"""
    # 停止音频文件自动清理任务
    await audio_manager.stop_auto_cleanup()
    print("🛑 应用关闭，音频自动清理任务已停止")

# 启动服务器
if __name__ == "__main__":
    uvicorn.run(
        "main:app", 
        host=settings.HOST, 
        port=settings.PORT, 
        reload=settings.RELOAD
    )